package com.cwd.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.cwd.constant.MessageConstant;
import com.cwd.entity.Result;
import com.cwd.service.MemberService;
import com.cwd.service.ReportService;
import com.cwd.service.SetmealService;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.data.JRBeanCollectionDataSource;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @PackageName: com.cwd.controller
 * @ClassName: ReportController
 * @Author: CWD
 * @Date: 2020/3/13 20:39
 * @Description:
 */
@RestController
@RequestMapping("/report")
public class ReportController {
    @Reference
    private MemberService memberService;
    @Reference
    private SetmealService setmealService;
    @Reference
    private ReportService reportService;
    //获取会员数量  ，用于页面会员数量的折线图统计图
    @RequestMapping("/getMemberReport")
    public Result getMemberReport(){
        Map<String,Object> map = new HashMap<>();  //封装月份和会员数量，用于返回给前台
        List<String> months = new ArrayList<>();   //用于存储月份
        Calendar calendar = Calendar.getInstance();  //获取日期对象，获得的时间就是当前的时间
        calendar.add(Calendar.MONTH,-12);    //当前时间向前推12个月，也就是一年
        for (int i = 0; i < 12; i++) {
            calendar.add(Calendar.MONTH,1);
            Date date = calendar.getTime();
            months.add(new SimpleDateFormat("yyyy-MM").format(date));
        }
        map.put("months",months);
        List<Integer> memberCount = memberService.findMemberCountByMonths(months);   //根据月份查询会员数量
        map.put("memberCount",memberCount);
        return new Result(true, MessageConstant.GET_MEMBER_NUMBER_REPORT_SUCCESS,map);
    }
    //获取套餐名称和预约数量，用于前台echarts百分比图表展示
    @RequestMapping("/getSetmealReport")
    public Result getSetmealReport(){
        Map<String,Object> data = new HashMap<>();
        try {
            //获取套餐的名称和套餐的预约数量
            List<Map<String,Object>> setmealCount = setmealService.findSetmealCount();
            List<String> setmealNames = new ArrayList<>();
            for (Map<String, Object> map : setmealCount) {
                //获取套餐名称
                String name = (String) map.get("name");
                setmealNames.add(name);
            }
            data.put("setmealNames",setmealNames);
            data.put("setmealCount",setmealCount);
            return new Result(true,MessageConstant.GET_SETMEAL_COUNT_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_SETMEAL_COUNT_REPORT_FAIL);
        }
    }
    //获取运营数据统计分析
    @RequestMapping("/getBusinessReportData")
    public Result getBusinessReportData(){
        try {
            Map<String,Object> data = new HashMap<>();
            data = reportService.getBusinessReportData();
            return new Result(true,MessageConstant.GET_BUSINESS_REPORT_SUCCESS,data);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
    //导出报表
    @RequestMapping("/exportBusinessReport")
    public Result exportBusinessReport(HttpServletRequest request, HttpServletResponse response){
        try {
            //获取运营统计数据
            Map<String, Object> map = reportService.getBusinessReportData();
            //取出数据，准备写入excel表中
            String reportDate = (String) map.get("reportDate");    //时间
            Integer todayNewMember = (Integer) map.get("todayNewMember");//今日新增会员数量
            Integer totalMember = (Integer) map.get("totalMember");      //会员总数量
            Integer thisWeekNewMember = (Integer) map.get("thisWeekNewMember");  //本周新增会员数量
            Integer thisMonthNewMember = (Integer) map.get("thisMonthNewMember");  //本月新增会员数量
            Integer todayOrderNumber = (Integer) map.get("todayOrderNumber");    //今日预约数量
            Integer thisWeekOrderNumber = (Integer) map.get("thisWeekOrderNumber"); //本周预约数量
            Integer thisMonthOrderNumber = (Integer) map.get("thisMonthOrderNumber");  //本月预约数量
            Integer todayVisitsNumber = (Integer) map.get("todayVisitsNumber");      //今日到诊人数
            Integer thisWeekVisitsNumber = (Integer) map.get("thisWeekVisitsNumber");   //本周到诊人数
            Integer thisMonthVisitsNumber = (Integer) map.get("thisMonthVisitsNumber");  //本月到诊人数
            List<Map> hotSetmeal = (List<Map>) map.get("hotSetmeal");        //热门套餐

            String filename = request.getSession().getServletContext().getRealPath("template") + File.separator + "report_template.xlsx";
            //基于提供的excel模板文件在内存中创建一个excel表格
            XSSFWorkbook excel = new XSSFWorkbook(new FileInputStream(new File(filename)));
            //读取第一个工作表
            XSSFSheet sheet = excel.getSheetAt(0);
            XSSFRow row = sheet.getRow(2);
            row.getCell(5).setCellValue(reportDate);   //设置表格中的日期
            row = sheet.getRow(4);
            row.getCell(5).setCellValue(todayNewMember); //设置本日新增会员数量
            row.getCell(7).setCellValue(totalMember);   //会员总数
            row = sheet.getRow(5);
            row.getCell(5).setCellValue(thisWeekNewMember); //本周新增会员总数
            row.getCell(7).setCellValue(thisMonthNewMember); //本月新增会员总数
            row = sheet.getRow(7);
            row.getCell(5).setCellValue(todayOrderNumber); //今日预约数
            row.getCell(7).setCellValue(todayVisitsNumber);  //今日到诊数
            row = sheet.getRow(8);
            row.getCell(5).setCellValue(thisWeekOrderNumber); //本周预约数
            row.getCell(7).setCellValue(thisWeekVisitsNumber); //本周到诊数
            row = sheet.getRow(9);
            row.getCell(5).setCellValue(thisMonthOrderNumber); //本月预约数
            row.getCell(7).setCellValue(thisMonthVisitsNumber);  //本月到诊数

            int rowNum = 12;
            for (Map setmeal : hotSetmeal) {
                String name = (String) setmeal.get("name");
                long setmeal_count = (Long) setmeal.get("setmeal_count");
                BigDecimal proportion = (BigDecimal) setmeal.get("proportion");
                row = sheet.getRow(rowNum++);
                row.getCell(4).setCellValue(name);
                row.getCell(5).setCellValue(setmeal_count);
                row.getCell(6).setCellValue(proportion.doubleValue());
            }
            //使用输出流进行excel表格下载 ，基于浏览器作为客户端下载
            OutputStream outputStream = response.getOutputStream();
            response.setContentType("application/vnd.ms-excel");
            response.setHeader("content-Disposition","attachment;filename=report.xlsx");
            excel.write(outputStream);
            outputStream.flush();
            outputStream.close();
            excel.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }

    //导出运营数据到PDF文件并提供客户端下载
    @RequestMapping("/exportBusinessReport4PDF")
    public Result exportBusinessReport4PDF(HttpServletRequest request, HttpServletResponse response){
        try{
            Map<String,Object> map = reportService.getBusinessReportData();

            //取出返回结果数据，准备将报表数据写入到Excel文件中
            List<Map> hotSetmealList = (List<Map>) map.get("hotSetmeal");

            //动态获取pdf模板文件绝对磁盘路径
            String jrxmlPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jrxml";
            String jasperPath = request.getSession().getServletContext().getRealPath("template") + File.separator + "health_business3.jasper";

            //编译模板
            JasperCompileManager.compileReportToFile(jrxmlPath, jasperPath);

            //填充数据---使用JavaBean数据源方式填充
            JasperPrint jasperPrint =
                    JasperFillManager.fillReport(jasperPath,map,
                            new JRBeanCollectionDataSource(hotSetmealList));

            //创建输出流，用于从服务器写数据到客户端浏览器
            ServletOutputStream out = response.getOutputStream();
            response.setContentType("application/pdf");
            response.setHeader("content-Disposition", "attachment;filename=report.pdf");

            //输出文件
            JasperExportManager.exportReportToPdfStream(jasperPrint,out);

            out.flush();
            out.close();

            return null;
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false, MessageConstant.GET_BUSINESS_REPORT_FAIL);
        }
    }
}
